package com.cnvp.paladin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;

import com.cnvp.paladin.core.BaseController;
import com.cnvp.paladin.kit.StringKit;
import com.cnvp.paladin.kit.tree.TreeKit;
import com.cnvp.paladin.model.Equipment;
import com.cnvp.paladin.model.SysDept;
import com.cnvp.paladin.model.SysRole;
import com.cnvp.paladin.model.SysUser;
import com.cnvp.paladin.model.SysUserRole;
import com.jfinal.kit.EncryptionKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class UserController extends BaseController {
    public void index() {
        setAttr("page", SysUser.dao.paginate(getParaToInt(0, 1), 10));
    }

    public void profile_app() {
        Map<String, Object> json = new HashMap<String, Object>();
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        json.put("data", currentUser);
        renderJson(json);
    }

    public void getlist() {
        Map<String, Object> json = new HashMap<String, Object>();
        List<SysUser> data = SysUser.dao.where("");
        json.put("data", data);
        renderJson(json);
    }

    public void create() {
        if (isPost()) {
            SysUser model = getModel(SysUser.class, "user");
            String psw = model.getStr("password");
            model.set("password", EncryptionKit.md5Encrypt(psw));
            model.set("create_time", System.currentTimeMillis());
            model.set("create_user_id", 1);
            if (model.save()) {
                model.deleteAllRoles();
                String[] role_ids = getParaValues("roles");
                if (role_ids != null)
                    for (String role_id : role_ids)
                        new SysUserRole().set("user_id", model.getInt("id")).set("role_id", role_id).save();
                redirect(getControllerKey());
                return;
            }
        }
        TreeKit deptTree = new TreeKit();
        deptTree.importModels(new SysDept().findByModel());
        // 所有角色数据
        setAttr("allroles", SysRole.dao.findAll());
        setAttr("depts", deptTree.getSelectMap());
        setAttr("data", new SysUser());
        render("form.html");
    }

    public void create_app() {
        if (isPost()) {
            SysUser model = getModel(SysUser.class, "user");
            String psw = model.getStr("password");
            model.set("password", EncryptionKit.md5Encrypt(psw));
            model.set("create_time", System.currentTimeMillis());
            model.set("create_user_id", 1);
            if (model.save()) {
                model.deleteAllRoles();
                String[] role_ids = getParaValues("roles");
                if (role_ids != null)
                    for (String role_id : role_ids)
                        new SysUserRole().set("user_id", model.getInt("id")).set("role_id", role_id).save();
                renderJson("{\"status\":\"success\"}");
                return;
            }
        }
        renderJson("{\"status\":\"failed\"}");
    }

    public void update() {
        
        if (isPost()) {
            SysUser model = getModel(SysUser.class, "user");
            if (StringKit.isBlank(getPara("user.password")))
                model.set("password", SysUser.dao.findById(getParaToInt()).get("password"));
            else {
                String psw = model.getStr("password");
                model.set("password", EncryptionKit.md5Encrypt(psw));
            }
            model.set("id", getParaToInt()).set("update_time", System.currentTimeMillis()).set("update_user_id", 1);
            if (model.update()) {
                model.deleteAllRoles();
                String[] role_ids = getParaValues("roles");
                if (role_ids != null)
                    for (String role_id : role_ids)
                        new SysUserRole().set("user_id", model.getInt("id")).set("role_id", role_id).save();
                redirect(getControllerKey());
            }
            return;
        }
        // 当前用户数据
        SysUser user = SysUser.dao.findById(getParaToInt());
        setAttr("data", user);
        // 部门select数据
        TreeKit deptTree = new TreeKit();
        deptTree.importModels(new SysDept().findByModel());
        setAttr("depts", deptTree.getSelectMap());
        // 所有角色数据
        setAttr("allroles", SysRole.dao.findAll());
        // 用户现有角色数据
        setAttr("useroles", user.getRoles());
        render("form.html");
    }

    public void update_app() {
        if (isPost()) {
            SysUser model = getModel(SysUser.class, "user");
            if (StringKit.isBlank(getPara("user.password")))
                model.set("password", SysUser.dao.findById(getParaToInt()).get("password"));
            else {
                String psw = model.getStr("password");
                model.set("password", EncryptionKit.md5Encrypt(psw));
            }
            model.set("id", getParaToInt()).set("update_time", System.currentTimeMillis()).set("update_user_id", 1);
            if (model.update()) {
                model.deleteAllRoles();
                String[] role_ids = getParaValues("roles");
                if (role_ids != null)
                    for (String role_id : role_ids)
                        new SysUserRole().set("user_id", model.getInt("id")).set("role_id", role_id).save();
                renderJson("{\"status\":\"success\"}");
                return;
            }
            renderJson("{\"status\":\"failed\"}");
            return;
        }
        renderJson("{\"status\":\"failed\"}");
        return;
    }

    public void delete() {
        SysUser model = SysUser.dao.findById(getParaToInt());
        if (model == null) {
            goBack();
            return;
        }
        if (SysUser.dao.findById(getParaToInt()).delete())
            redirect(getControllerKey());
        else
            goBack();
    }

    public void delete_app() {
        SysUser model = SysUser.dao.findById(getParaToInt());
        if (model == null) {
            renderJson("{\"status\":\"failed(user_no_exist)\"}");
            return;
        }
        if (SysUser.dao.findById(getParaToInt()).delete())
            renderJson("{\"status\":\"success\"}");
        else
            renderJson("{\"status\":\"delete_failed\"}");
    }

    public void deleteAll() {
        Integer[] ids = getParaValuesToInt("id");
        for (Integer id : ids) {
            SysUser.dao.findById(id).delete();
            // System.out.println(id);
        }
        redirect(getControllerKey());
    }

    public void password() {
        String is_app = getPara("is_app");
        if ("POST".equals(getRequest().getMethod())) {
            SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            int id = currentUser.get("id");
            String sqlFind = "select * from cnvp_sys_user where id =" + "\"" + id + "\";";
            //currentUser = SysUser.dao.findById(currentUser.get("id"));
            String old = getPara("old");
            String new1 = getPara("new1");
            String new2 = getPara("new2");

            // 先判断is_app是否为null
            if (is_app != null && is_app.equals("1")) {
                if (StringKit.isBlank(old))
                    renderJson("{\"code\":\"310\",\"data\":\"\",\"msg\":\"原始密码不能为空\"}");
                else if (!currentUser.getStr("password").equals(EncryptionKit.md5Encrypt(old)))
                    renderJson("{\"code\":\"311\",\"data\":\"\",\"msg\":\"原始密码错误\"}");
                else if (!new1.equals(new2))
                    renderJson("{\"code\":\"312\",\"data\":\"\",\"msg\":\"新密码两次输入不一致\"}");
                else {
                    List<Record> user = Db.find(sqlFind);
                    for (int i = 0; i < user.size(); i++)
                        Db.update("cnvp_sys_user", user.get(i).set("password", EncryptionKit.md5Encrypt(new1)));
                    renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"密码修改成功\"}");

                }
            } else {
                if (StringKit.isBlank(old))
                    alertAndGoback("原始密码不能为空");
                else if (!currentUser.getStr("password").equals(EncryptionKit.md5Encrypt(old)))
                    alertAndGoback("原始密码错误");
                else if (!new1.equals(new2))
                    alertAndGoback("新密码两次输入不一致");
                else {
                    List<Record> user = Db.find(sqlFind);
                    for (int i = 0; i < user.size(); i++)
                        Db.update("cnvp_sys_user", user.get(i).set("password", EncryptionKit.md5Encrypt(new1)));
                    alertAndGoback("密码修改成功");

                }
            }
        }
    }



    public void email() {
        String is_app = getPara("is_app");
        if ("POST".equals(getRequest().getMethod())) {
            SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            int id = currentUser.get("id");
            String sqlFind = "select * from cnvp_sys_user where id =" + "\"" + id + "\";";

            String old = getPara("old");
            String new1 = getPara("new1");
            String new2 = getPara("new2");

            // 先判断is_app是否为null
            if (is_app != null && is_app.equals("1")) {

                if (StringKit.isBlank(old))
                    renderJson("{\"code\":\"310\",\"data\":\"\",\"msg\":\"原始邮箱不能为空\"}");
                else if (!currentUser.getStr("email").equals(old))
                    renderJson("{\"code\":\"311\",\"data\":\"\",\"msg\":\"原始邮箱错误\"}");
                else if (!new1.equals(new2))
                    renderJson("{\"code\":\"312\",\"data\":\"\",\"msg\":\"新邮箱两次输入不一致\"}");
                else {
                    List<Record> user = Db.find(sqlFind);
                    for (int i = 0; i < user.size(); i++)
                        Db.update("cnvp_sys_user", user.get(i).set("email", new1));
                }

            } else {

                if (StringKit.isBlank(old))
                    alertAndGoback("原始邮箱不能为空");
                else if (!currentUser.getStr("email").equals(old))
                    alertAndGoback("原始邮箱错误");
                else if (!new1.equals(new2))
                    alertAndGoback("新邮箱两次输入不一致");
                else {
                    List<Record> user = Db.find(sqlFind);
                    for (int i = 0; i < user.size(); i++)
                        Db.update("cnvp_sys_user", user.get(i).set("email", new1));
                }

            }

        }
    }
}
